<template>
  <div class="app-container">
    <el-card style="border-radius: 10px">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
        <el-form-item label="检验单编号" prop="ipqcCode">
          <el-input
            v-model="queryParams.ipqcCode"
            placeholder="请输入检验单编号"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>

        <el-form-item label="工单编号" prop="workorderCode">
          <el-input
            v-model="queryParams.workorderCode"
            placeholder="请输入工单编码"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="产品物料编码" prop="itemCode">
          <el-input
            v-model="queryParams.itemCode"
            placeholder="请输入产品物料编码"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="产品物料名称" prop="itemName">
          <el-input
            v-model="queryParams.itemName"
            placeholder="请输入产品物料名称"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="检测结果" prop="checkResult">
          <el-select v-model="queryParams.checkResult" placeholder="请选择检验结果" clearable>
            <el-option
              v-for="dict in dict.type.mes_qc_result"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <div style="height: 15px"></div>
    <el-card style="border-radius: 10px">
<!--      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['mes:qc:ipqc:add']"
          >新增
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            icon="el-icon-edit"
            size="mini"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['mes:qc:ipqc:edit']"
          >修改
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['mes:qc:ipqc:remove']"
          >删除
          </el-button>
        </el-col>
&lt;!&ndash;        <el-col :span="1.5">
          <el-button
            type="warning"
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            v-hasPermi="['mes:qc:ipqc:export']"
          >导出
          </el-button>
        </el-col>&ndash;&gt;
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>-->

      <el-table border v-loading="loading" :data="ipqcList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="50" align="center"/>
        <el-table-column label="检验单编号" width="140" align="center" prop="ipqcCode">
          <template slot-scope="scope">
            <el-button
              type="text"
              @click="handleView(scope.row)"
              v-hasPermi="['mes:qc:ipqc:query']"
            >{{ scope.row.ipqcCode }}
            </el-button>
          </template>
        </el-table-column>

        <el-table-column label="工单编号" width="140" align="center" prop="workorderCode"/>
        <el-table-column label="产品物料编码" width="140" align="center" prop="itemCode"/>
        <el-table-column label="产品物料名称" align="center" prop="itemName" :show-overflow-tooltip="true"/>
        <el-table-column label="规格型号" align="center" prop="specification" :show-overflow-tooltip="true"/>
        <el-table-column label="单位" align="center" prop="unitOfMeasure" :show-overflow-tooltip="true"/>
        <el-table-column label="检测数量" align="center" prop="quantityCheck"/>
        <el-table-column label="检测结果" width="80" align="center" prop="checkResult"  :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.mes_qc_result" :value="scope.row.checkResult"/>
          </template>
        </el-table-column>

        <el-table-column label="检测日期" align="center" prop="inspectDate" width="120">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.inspectDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="检测人员" align="center" prop="inspector"/>
        <el-table-column label="单据状态" width="80" align="center" prop="status">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.mes_order_status" :value="scope.row.status"/>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="120px">
          <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-if="scope.row.status == 'PREPARE'"
                v-hasPermi="['mes:qc:ipqc:edit']"
              >修改</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-if="scope.row.status == 'PREPARE'"
                v-hasPermi="['mes:qc:ipqc:remove']"
              >删除</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-printer"
                @click="handlePrint(scope.row)"
                v-if="scope.row.status === 'FINISHED' || scope.row.status === 'CONFIRMED'"
                v-hasPermi="['mes:qc:ipqc:edit']"
              >打印</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>
    <!-- 添加或修改过程检验单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1200px" append-to-body>
      <pqc-info ref="pqcInfo" :form="form" ></pqc-info>
      <el-divider content-position="center" >检验信息</el-divider>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="检验单编号" prop="ipqcCode">
              <el-input v-model="form.ipqcCode" :optType="optType" readonly placeholder="请输入检验单编号"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="检验单名称" prop="ipqcName">
              <el-input v-model="form.ipqcName" :optType="optType" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="检测数量" prop="quantityCheck">
              <el-input v-model="form.quantityCheck" readonly  :optType="optType"  placeholder="请输入检测数量"/>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="合格品数量" prop="quantityQualified">
              <el-input-number
                :optType="optType"
                :min="0"
                :max="form.quantityCheck"
                v-model="form.quantityQualified"
                @change="jiSuanBuHege()"
                placeholder="请输入合格数量"
                :disabled="ipqclineList.length>0"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="不合格数" prop="quantityUnqualified">
              <el-input-number
                :min="0"
                :optType="optType"
                :max="form.quantityCheck"
                :disabled="ipqclineList.length>0"
                @change="jiSuanHege()"
                v-model="form.quantityUnqualified"
                placeholder="请输入不合格数量"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="检测日期" prop="inspectDate">
              <el-date-picker clearable
                              v-model="form.inspectDate"
                              type="date"
                              :optType="optType"
                              value-format="yyyy-MM-dd"
                              placeholder="请选择检测日期">
              </el-date-picker>

            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="检测结果" prop="checkResult">
              <el-select :optType="optType" v-model="form.checkResult" placeholder="请选择检验结果">
                <el-option
                  v-for="dict in dict.type.mes_qc_result"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="检测人员" prop="inspector">
              <el-input v-model="form.inspector" placeholder="请输入检测人员"  :optType="optType"  readonly>
                <el-button :optType="optType" slot="append" @click="handleSelectUser" icon="el-icon-search"></el-button>
              </el-input>
              <UserSelect ref="userSelect" @onSelected="onUserSelected" ></UserSelect>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark" :optType="optType">
              <el-input v-model="form.remark" type="textarea" :optType="optType" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="附件" prop="remark">
              <FileUpload
                :limit="5"
                :fileSize="100"
                :fileType="fileType"
                :value="fileList"
                :optType="optType"
                @onUploaded="handleUploaded"
                @onRemoved="handleRemoved">
              </FileUpload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-divider v-if="form.ipqcId !=null" content-position="center">检测项</el-divider>
      <el-card shadow="always" v-if="form.ipqcId !=null" class="box-card">
        <Ipqcline ref="line" v-if="ipqclineList.length>0" :ipqclineListFromParent="ipqclineList" :realValueColumnsFromParent="realValueColumns"  :optType="optType"  @computeValue="computeValue1"></Ipqcline>
      </el-card>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="cancel" v-if="optType =='view' || form.status !='PREPARE' ">返回</el-button>
        <el-button type="primary" @click="submitForm" v-if="form.status =='PREPARE' && optType !='view' ">保 存
        </el-button>
        <el-button type="success" @click="handleFinish"
                   v-if="form.status =='PREPARE' && optType !='view'  && form.ipqcId !=null">完成
        </el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <IpqcPrint ref="ipqcPrint" v-if="printvisible"></IpqcPrint>
  </div>
</template>

<script>
import { addIpqc, delIpqc, getIpqc, listIpqc, updateIpqc, addRrIpqc, updateRrIpqc } from "@/api/mes/qc/ipqc";
import { genCode } from "@/api/system/autocode/rule"
import WorkorderSelect from "@/components/workorderSelect/single.vue"
import ProtaskSelect from "@/components/TaskSelect/taskSelectSingle.vue";
import Ipqcline from "./line.vue"
import UserSelect from "@/components/userSelect/single.vue";
import { getUserProfile } from "@/api/system/user";
import IpqcPrint from "@/views/mes/qc/ipqc/print.vue";
import pqcInfo from "@/views/mes/qc/pendinginspect/pqcInfo.vue";
import {listNoPage} from "@/api/mes/qc/ipqcline";

export default {
  name: "Ipqc",
  components: {pqcInfo, IpqcPrint, WorkorderSelect, ProtaskSelect, Ipqcline, UserSelect},
  dicts: ['mes_ipqc_type', 'mes_qc_result', 'mes_order_status'],
  data() {
    return {
      // 过程检验单行表格数据
      ipqclineList: [],
      realValueColumns:[],
      resultArray:[],
      printvisible: false,
      activeNames: '1',
      optType: undefined,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 过程检验单表格数据
      ipqcList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        ipqcCode: null,
        ipqcName: null,
        ipqcType: null,
        templateId: null,
        workorderId: null,
        workorderCode: null,
        workorderName: null,
        taskId: null,
        taskCode: null,
        taskName: null,
        workstationId: null,
        workstationCode: null,
        workstationName: null,
        processId: null,
        processCode: null,
        processName: null,
        itemId: null,
        itemCode: null,
        itemName: null,
        specification: null,
        unitOfMeasure: null,
        quantityCheck: null,
        quantityUnqualified: null,
        quantityQualified: null,
        crRate: null,
        majRate: null,
        minRate: null,
        crQuantity: null,
        majQuantity: null,
        minQuantity: null,
        checkResult: null,
        inspectDate: null,
        inspector: null,
        status: null,
      },
      // 表单参数
      form: {},
      // 上传文件类型
      fileType: ["pdf","doc", "xls","jpg","png"],
      // 上传文件列表
      fileList: [],
      // 表单校验
      rules: {
        ipqcCode: [
          {required: true, message: "请输入生产检验单编号", trigger: "blur"}
        ],
        ipqcType: [
          {required: true, message: "请选择检验类型", trigger: "change"}
        ],

        workorderCode: [
          {required: true, message: "请选择生产工单", trigger: "blur"}
        ],

        workstationCode: [
          {required: true, message: "请选择工作站", trigger: "blur"}
        ],

        quantityCheck: [
          {required: true, message: "检测数量不能为空", trigger: "blur"}
        ],

        quantityUnqualified: [
          {required: true, message: "不合格品数量不能为空", trigger: "blur"}
        ],
        quantityQualified: [
          {required: true, message: "合格品数量不能为空", trigger: "blur"}
        ],
        taskCode: [
          {required: true, message: "请选择任务", trigger: "blur"}
        ],
        checkResult:[
          {required: true, message: "检测结果不能为空", trigger: "blur"}
        ],
      },
      // 当前登录用户
      user: null,
    };
  },
  created() {
    this.reset();
    this.getList();
    this.getUser();
  },
  methods: {
    jiSuanBuHege(){
      if(this.ipqclineList==0){
        this.form.quantityUnqualified=this.form.quantityCheck-this.form.quantityQualified;
      }
    },
    jiSuanHege(){
      if(this.ipqclineList==0){
        this.form.quantityQualified=this.form.quantityCheck-this.form.quantityUnqualified;
      }
    },
    setRealValueColumns1(){
      this.realValueColumns= Array.from({length: this.form.quantityCheck}, (_, index) => {
        return {
          label: '实际值'+(index+1),
          prop: 'realValue'+(index+1),
          width: 150
        }
      });
      this.resultArray=Array.from({length: this.form.quantityCheck});
    },
    setRealValueColumns2(){
      this.realValueColumns= Array.from({length: this.ipqclineList[0].realValues.length}, (_, index) => {
        return {
          label: '实际值'+(index+1),
          prop: 'realValue'+(index),
          width: 150
        }
      });
      this.resultArray=Array.from({length: this.ipqclineList[0].realValues.length});
    },
    /** 查询过程检验单行列表 */
    getLineList() {
      listNoPage({ipqcId: this.form.ipqcId}).then(response => {
        this.ipqclineList = response.data;
        console.log(this.ipqclineList)
        if(this.ipqclineList.length>0&&this.ipqclineList[0].realValues!=null){
          this.setRealValueColumns2();
        }else{
          this.setRealValueColumns1();
        }
        this.ipqclineList.map(item => {
          if(item.realValues==null) {
            let defaultV=0;
            if(item.indexType == 'QUALITATIVE'){
              defaultV=1;
            }
            let realValues = [];
            for (let i = 1; i <= this.form.quantityCheck; i++) {
              realValues.push(defaultV);
            }
            this.$set(item, 'realValues', realValues);
          }
        })
        this.open = true;
      });
    },
    computeValue1(ipqclineList){
      this.realValueColumns.forEach((it,index)=>{
        let result=true;
        ipqclineList.forEach(item => {
          //定性
          if(item.indexType == 'QUALITATIVE'){
            if(item.realValues[index]==0){
              result=false;
              return;
            }
          }else{
            if(item.realValues[index]<item.standerVal+item.thresholdMin||item.realValues[index]>item.standerVal+item.thresholdMax){
              result=false;
              return;
            }
          }
        });
        this.resultArray[index]=result;
      })
      let heGeShu=0;
      let buHeGeShu=0;
      this.resultArray.forEach(i=> {
        if(i!=null){
          if(i) {
            heGeShu++;
          }else{
            buHeGeShu++;
          }
        }
      })
      this.form.quantityQualified=heGeShu;
      this.form.quantityUnqualified = buHeGeShu;
    },
    /** 查询过程检验单列表 */
    getList() {
      this.loading = true;
      listIpqc(this.queryParams).then(response => {
        this.ipqcList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        ipqcId: null,
        ipqcCode: null,
        ipqcName: null,
        ipqcType: null,
        templateId: null,
        workorderId: null,
        workorderCode: null,
        workorderName: null,
        taskId: null,
        taskCode: null,
        taskName: null,
        workstationId: null,
        workstationCode: null,
        workstationName: null,
        processId: null,
        processCode: null,
        processName: null,
        itemId: null,
        itemCode: null,
        itemName: null,
        specification: null,
        unitOfMeasure: null,
        quantityCheck: null,
        quantityUnqualified: null,
        quantityQualified: null,
        crRate: null,
        majRate: null,
        minRate: null,
        crQuantity: null,
        majQuantity: null,
        minQuantity: null,
        checkResult: null,
        inspectDate: new Date(),
        inspector: null,
        status: "PREPARE",
        remark: null,
        attr1: null,
        attr2: null,
        attr3: null,
        attr4: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.resetForm("form");
      this.fileList = [];
      this.ipqclineList = [];
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.ipqcId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.form.inspector = this.user.nickName;
      this.open = true;
      this.title = "添加过程检验单";
      this.optType = "add";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.getIpqcMes(row,'edit','修改过程检验单')
    },
    handleReset() {
      getIpqc(this.form.ipqcId).then(response => {
        this.form.crQuantity = response.data.crQuantity;
        this.form.majQuantity = response.data.majQuantity;
        this.form.minQuantity = response.data.minQuantity;
      });
    },
    //查看单据
    handleView(row) {
      this.getIpqcMes(row,'view','查看过程检验单')
    },
    getIpqcMes(row,optType,title){
      this.reset();
      const ipqcId = row.ipqcId
      getIpqc(ipqcId).then(response => {
        this.form = response.data;
        this.form.attr2 = response.data.attr2;
        response.data.attr2 === null ? this.fileList = [] : this.fileList.push(response.data.attr2);
        this.getLineList();
        this.title =title;
        this.optType =optType;
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if(this.form.sourceDocType =='返修报工'){
            if (this.form.ipqcId != null) {
              updateRrIpqc(this.form).then((response) => {
                this.$modal.msgSuccess('修改成功')
              })
            } else {
              addRrIpqc(this.form).then((response) => {
                this.$modal.msgSuccess('新增成功')
                this.form.ipqcId = response.data //将返回的ID保存
              })
            }
          }else {
            if (this.form.ipqcId != null) {
              updateIpqc(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                //this.open = false;
                this.getList();
              });
            } else {
              addIpqc(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.form.ipqcId = response.data; //将返回的ID保存
                //this.open = false;
                this.getList();
              });
            }
          }
        }
      });
    },
    //点击完成
    handleFinish() {
      let that = this;
      if (this.form.checkResult == null) {
        this.$modal.msgError("请选择检测结果！");
        return;
      }
      let num = parseInt(that.form.quantityCheck);
      let he = parseInt(that.form.quantityQualified) + parseInt(that.form.quantityUnqualified)
      if (num !== he) {
        this.$modal.msgError("合格品数量与不合格品数量之和不等于检测数量！")
        return;
      }
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.$modal.confirm('是否完成检验单编制？【完成后将不能更改】').then(function () {
            if (that.form.sourceDocId) {
              that.form.status = 'FINISHED';
            } else {
              that.form.status = 'CONFIRMED';
            }
            that.submitForm();
            that.open = false;
          });
        }
      });
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const ipqcIds = row.ipqcId || this.ids;
      this.$modal.confirm('是否确认删除过程检验单编号为"' + ipqcIds + '"的数据项？').then(function () {
        return delIpqc(ipqcIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('qc/ipqc/export', {
        ...this.queryParams
      }, `ipqc_${new Date().getTime()}.xlsx`)
    },
    //选择生产工单
    handleWorkorderSelect() {
      this.$refs.woSelect.showFlag = true;
    },
    onWorkorderSelected(row) {
      if (row != undefined && row != null) {
        this.form.workorderId = row.workorderId;
        this.form.workorderCode = row.workorderCode;
        this.form.workorderName = row.workorderName;
        this.form.itemId = row.productId;
        this.form.itemCode = row.productCode;
        this.form.itemName = row.productName;
        this.form.specification = row.productSpc;
        this.form.unitOfMeasure = row.unitOfMeasure;

      }
    },
    handleTaskSelect() {
      this.$refs.taskSelect.showFlag = true;
      this.$refs.taskSelect.getList();
    },
    onTaskSelected(row) {
      if (row != undefined && row != null) {
        this.form.taskId = row.taskId;
        this.form.taskCode = row.taskCode;
        this.form.taskName = row.taskName;
        this.form.workstationId = row.workstationId;
        this.form.workstationCode = row.workstationCode;
        this.form.workstationName = row.workstationName;
        this.form.processId = row.processId;
        this.form.processCode = row.processCode;
        this.form.processName = row.processName;

      }
    },

    handleSelectUser(){
      this.$refs.userSelect.showFlag = true;
    },
    // 用户选择弹出框
    onUserSelected(obj){
      if(obj != undefined && obj != null){
        this.form.inspector = obj.nickName;
      }
    },
    // 获取登录用户
    getUser() {
      getUserProfile().then(response => {
        this.user = response.data;
      });
    },
    handleUploaded(data) {
      this.form.attr2 = data;
    },
    handleRemoved(data) {
      this.form.attr2 = data;
    },
    // 打印
    handlePrint(row) {
      this.printvisible = true;
      this.$nextTick(() => {
        this.$refs.ipqcPrint.init(row.ipqcId);
      })
    },
  }
};
</script>
<style lang="scss" >
.el-divider--horizontal{
  height: 2px;
  background-color: #b2b4b9;
}

</style>
